package old.day20190320.shiwu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author DingZhenYun
 * @create 2019-03-20 19:49
 *  关于事务: 1. 如果多个操作, 每个操作使用的是自己的单独的连接, 则无法保证事务. 2. 具体步骤: 1). 事务操作开始前, 开始事务:
 * 	 * 取消 Connection 的默认提交行为. connection.setAutoCommit(false); 2). 如果事务的操作都成功,
 * 	 * 则提交事务: connection.commit(); 3). 回滚事务: 若出现异常, 则在 catch 块中回滚事务:
 */
public class Test {
    public static void main(String[] args) {
        Test t=new Test();
        t.testTransaction();
    }
    public static void update(Connection conn,String sql,Object ... args){
        PreparedStatement preparedStatement=null;
        try {
            preparedStatement=conn.prepareStatement(sql);

            for(int i=0;i<args.length;i++){
                preparedStatement.setObject(i+1,args[i]);
            }
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCTools.releaseDB(null,preparedStatement,conn);
        }
    }
    private  void testTransaction() {
        /*
        违背一致性
        DAO dao=new DAO();
        String sql="update user set balance=balance-500 where id=1";
        String sql1="update user set balance=balance+500 where id=2";
        dao.update(sql);
        int i=10/0;
        System.out.println(i);
        dao.update(sql1);
        */
        /*
         * try {
         *
         * //开始事务: 取消默认提交. connection.setAutoCommit(false);
         *
         * //...
         *
         * //提交事务 connection.commit(); } catch (Exception e) { //...
         *
         * //回滚事务 try { connection.rollback(); } catch (SQLException e1) {
         * e1.printStackTrace(); } } finally{ JDBCTools.releaseDB(null, null,
         * connection); }
         */
        Connection connection=null;
        try{
            connection=JDBCTools.getConnection();
            //开始事务: 取消默认提交.
            connection.setAutoCommit(false);
            String sql="update user set balance=balance-500 where id=1";
            update(connection,sql);
            int i=10/0;
            System.out.println(i);
            String sql1="update user set balance=balance+500 where id=2";
            update(connection,sql1);
            //提交事务
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            JDBCTools.releaseDB(null,null,connection);
        }
    }

}
